package com.cb.util;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.springframework.beans.factory.annotation.Autowired;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;

public class RsaUtil {
	public static String KEY_PAIRGENO = "RSA";  
    public static String PUBLIC_KEY = "PUBLIC_KEY";  
    public static String PRIVATE_KEY = "PRIVATE_KEY";  
    
    public final static String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYQOl+hkiFUzr0OnCFuBqyVFoHHiyexh38vILgxq3vUL/Dfavcvzef+xB0PuR8sQyXSnq8IoDCm/727pCI/n0ZGG/ygGbTw0FiXG8WvtVGWMrO6yf84Dr6lY1CKrlowgTqkZhEAUyzEHfqrAvaurRHzS035y58VX2faHfdECZZUQIDAQAB";
    public final static String priKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANhA6X6GSIVTOvQ6cIW4GrJUWgceLJ7GHfy8guDGre9Qv8N9q9y/N5/7EHQ+5HyxDJdKerwigMKb/vbukIj+fRkYb/KAZtPDQWJcbxa+1UZYys7rJ/zgOvqVjUIquWjCBOqRmEQBTLMQd+qsC9q6tEfNLTfnLnxVfZ9od90QJllRAgMBAAECgYB1lrZgajw84wkHjE9rJrS9i0h43lt86lWb/BVejCpAGzRq5IbzPbbNcwN7ckdj1hH2ojUi39AMAi8drpNBKsBySHVCkv8iO/ofXCNpHKpTah9qxmIx/vPMv9LpuNoTKdmRCiWXlHrim/ROTdy9c34lB82tjHchfhInbY9e3OQ6kQJBAPupZ8AQm2VgMbiP39KHQU/2g6h+7tBdxdyj7g/Cu8+YasDQzsPvmjyCjvJFoHDwYtTMuz/0NhgO9OQKk7NgMTsCQQDb+z+48IwFSYC1UqmpTH8C47fdnwYQvfHFwibSF9XscRN8mG9kQMywRwHFBD4jD+UK3N74DeS7yFZTaeSO5PbjAkEAqthfmbDsfc7nEj+CGD9AJJPa32mEoKn4aAhV1hdCPvVfC5T1uWiQ0aFkf66q8+ENhx+RwyH8EyscLy/LA4w6/wJBAKcDqYyi7Nvyw0pnOTK1RlUOSQF1A+jgHViUoF6wBBXgf/f/z8qgvAc10e0f3IFIRxApQwu3mKrNXmU0J3gp9BsCQQDSkRdo4Dvv+anCeLKoUcUhD1oGjpsI5eHWP3/gQ4hnIWgJMkg0qwM/zBGk7x5SY8+6mc8KaJ4mvMvEZHQGOn6C";
  
    public static HashMap<String, Object> keyMap;  
  
    public static HashMap<String, Object> initKey() throws Exception {  
        KeyPairGenerator keyPairGeno = KeyPairGenerator  
                .getInstance("RSA");  
        keyPairGeno.initialize(1024);  
        KeyPair keyPair = keyPairGeno.generateKeyPair();  
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
        keyMap = new HashMap<String, Object>(2);  
        keyMap.put(PUBLIC_KEY, publicKey);  
        keyMap.put(PRIVATE_KEY, privateKey);  
        return keyMap;  
    }  
  
    public static String getPublicKey() {  
        Key key = (Key) keyMap.get(PUBLIC_KEY);  
        byte[] bytes = key.getEncoded();  
        return Base64.encode(bytes);  
    }  
  
    public static String getPrivateKey() {  
        Key key = (Key) keyMap.get(PRIVATE_KEY);  
        byte[] bytes = key.getEncoded();  
          
        return Base64.encode(bytes);  
    }  
  
    // 通过公钥byte[]将公钥还原，适用于RSA算法  
  
    public static PublicKey getPublicKey(byte[] keyBytes) throws Exception {  
          
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
        PublicKey publicKey = keyFactory.generatePublic(keySpec);  
  
        return publicKey;  
  
    }  
  
    // 通过私钥byte[]将公钥还原，适用于RSA算法  
  
    public static PrivateKey getPrivateKey(byte[] keyBytes) throws Exception {  
  
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);  
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);  
        return privateKey;  
  
    }  
  
    /**  
     * 公钥加密  
     *   
     * @param data  
     * @param publicKey  
     * @return  
     * @throws Exception  
     */  
    public static String encryptByPublicKey(String data, RSAPublicKey publicKey)  
            throws Exception {  
        Cipher cipher = Cipher.getInstance(KEY_PAIRGENO);  
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
        // 模长  
        int key_len = publicKey.getModulus().bitLength() / 8;  
        // 加密数据长度 <= 模长-11  
        String[] datas = splitString(data, key_len - 11);  
        String mi = "";  
        // 如果明文长度大于模长-11则要分组加密  
        for (String s : datas) {  
            mi += bcd2Str(cipher.doFinal(s.getBytes()));  
        }  
        return mi;  
    }  
  
    /**  
     * 私钥解密  
     *   
     * @param data  
     * @param privateKey  
     * @return  
     * @throws Exception  
     */  
    public static String decryptByPrivateKey(String data,  
            RSAPrivateKey privateKey) throws Exception {  
        Cipher cipher = Cipher.getInstance(KEY_PAIRGENO);  
        cipher.init(Cipher.DECRYPT_MODE, privateKey);  
        // 模长  
        int key_len = privateKey.getModulus().bitLength() / 8;  
        byte[] bytes = data.getBytes();  
        byte[] bcd = ASCII_To_BCD(bytes, bytes.length);  
        // 如果密文长度大于模长则要分组解密  
        String ming = "";  
        byte[][] arrays = splitArray(bcd, key_len);  
        for (byte[] arr : arrays) {  
            ming += new String(cipher.doFinal(arr));  
        }  
        return ming;  
    }  
  
    /**  
     * ASCII码转BCD码  
     *   
     */  
    public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {  
        byte[] bcd = new byte[asc_len / 2];  
        int j = 0;  
        for (int i = 0; i < (asc_len + 1) / 2; i++) {  
            bcd[i] = asc_to_bcd(ascii[j++]);  
            bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));  
        }  
        return bcd;  
    }  
  
    public static byte asc_to_bcd(byte asc) {  
        byte bcd;  
  
        if ((asc >= '0') && (asc <= '9'))  
            bcd = (byte) (asc - '0');  
        else if ((asc >= 'A') && (asc <= 'F'))  
            bcd = (byte) (asc - 'A' + 10);  
        else if ((asc >= 'a') && (asc <= 'f'))  
            bcd = (byte) (asc - 'a' + 10);  
        else  
            bcd = (byte) (asc - 48);  
        return bcd;  
    }  
  
    /**  
     * BCD转字符串  
     */  
    public static String bcd2Str(byte[] bytes) {  
        char temp[] = new char[bytes.length * 2], val;  
  
        for (int i = 0; i < bytes.length; i++) {  
            val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);  
            temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');  
  
            val = (char) (bytes[i] & 0x0f);  
            temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');  
        }  
        return new String(temp);  
    }  
  
    /**  
     * 拆分字符串  
     */  
    public static String[] splitString(String string, int len) {  
        int x = string.length() / len;  
        int y = string.length() % len;  
        int z = 0;  
        if (y != 0) {  
            z = 1;  
        }  
        String[] strings = new String[x + z];  
        String str = "";  
        for (int i = 0; i < x + z; i++) {  
            if (i == x + z - 1 && y != 0) {  
                str = string.substring(i * len, i * len + y);  
            } else {  
                str = string.substring(i * len, i * len + len);  
            }  
            strings[i] = str;  
        }  
        return strings;  
    }  
  
    /**  
     *拆分数组  
     */  
    public static byte[][] splitArray(byte[] data, int len) {  
        int x = data.length / len;  
        int y = data.length % len;  
        int z = 0;  
        if (y != 0) {  
            z = 1;  
        }  
        byte[][] arrays = new byte[x + z][];  
        byte[] arr;  
        for (int i = 0; i < x + z; i++) {  
            arr = new byte[len];  
            if (i == x + z - 1 && y != 0) {  
                System.arraycopy(data, i * len, arr, 0, y);  
            } else {  
                System.arraycopy(data, i * len, arr, 0, len);  
            }  
            arrays[i] = arr;  
        }  
        return arrays;  
    }
    
    /**
     * 密文
     * @param content	需要加密的内容
     * @return
     * @throws Base64DecodingException
     * @throws Exception
     */
    public static String encryptByPublicKey(String content) throws Base64DecodingException, Exception{
    	String encrypt = RsaUtil.encryptByPublicKey(content, (RSAPublicKey)RsaUtil.getPublicKey(Base64.decode(pubKey)));
		return encrypt;
    }
    
    /**
     * 解密
     * @param encrypt	需要解密的内容
     * @return
     * @throws Base64DecodingException
     * @throws Exception
     */
    public static String decryptByPrivateKey(String encrypt) throws Base64DecodingException, Exception{
    	String content = RsaUtil.decryptByPrivateKey(encrypt,(RSAPrivateKey)RsaUtil.getPrivateKey(Base64.decode(priKey)));
		return content;
    }
    
    public static void main(String[] args) throws Exception {  
    	Map rep=new HashMap();
        try {  
        	rep=RsaUtil.initKey();//执行完后可通过getPublicKey()或getPrivateKey()方法获取这这一对密钥(随机生成)  
        } catch (Exception e) {  	
            e.printStackTrace();  
        }  
        
        System.out.println("用公钥加密  pubKey:"+pubKey);
        System.out.println("用私钥解密  priKey:"+priKey);
        
        String content = "2018-12-30";  
        //用公钥加密  
        String miwen = encryptByPublicKey(content);  
        System.out.println("密文 : "+miwen);  
        //用私钥解密  
        System.out.println("解密 : "+decryptByPrivateKey(miwen));  
       }  
}